package com.woniuxy.array02;

import java.util.Arrays;

/**
 * description: Test04 <br>
 * date: 2022/2/1 9:44 下午 <br>
 * author: shesaifei <br>
 * version: 1.0 <br>
 */
//二分法查询

public class Test04 {
    public static void main(String[] args) {
        int[] arr = {10, 30, 58, 12, 13};
        //必须是排好序的
        Arrays.sort(arr);
        int value = 12;
        System.out.println(Arrays.toString(arr));
        System.out.println(myBinarySearch(arr, value));
    }

    public static int myBinarySearch(int[] arr, int value) {
        //起始位置
        int low = 0;
        //结束位置
        int high = arr.length - 1;
        while (low <= high) {
            int mid = (low + high) / 2;
            if (value == arr[mid]) {
                return mid;
            }
            if (value > arr[mid]) {
                low = mid + 1;
            }
            if (value < arr[mid]) {
                high = mid - 1;
            }
        }
        return -1;
    }
}